package com.gjintel.framework.common.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gjintel.auction.business.model.AuctionInfo;
import com.gjintel.auction.business.service.IAuctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gjintel.business.proj.dao.IDepositReturnDao;
import com.gjintel.business.proj.model.ComposeIdPK;
import com.gjintel.business.proj.model.ComposeIdPK2;
import com.gjintel.business.proj.model.DepositReturn;
import com.gjintel.business.proj.model.DepositReturnOut;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.service.IDepositReturnService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.framework.common.service.IDepositService;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.SocketUtil;
import com.gjintel.framework.util.XmlParserUtil;
import com.gjintel.framework.util.dto.Bank;
import com.gjintel.framework.util.dto.Head;
import com.gjintel.framework.util.dto.JXml;

@Service("depositService")
@SuppressWarnings("all")
public class DepositServiceImpl implements IDepositService {

	@Value("${bank.serverIp}")
	private String bankServerIp;
	
	@Value("${bank.serverPort}")
	private String bankServerPort;
	
	//采购中心的银行帐号
	@Value("${center.account}")
	private String centerAccount;   
	final String modelPath = URLDecoder.decode(IDepositService.class.getResource("/bank").getPath(),"utf-8");
	@Autowired
	private IProjectInfoService projectInfoService;

	@Autowired
	private IDepositReturnService depositService;
	
	@Autowired
	private IDepositReturnDao depositReturnDao;

	@Autowired
	private IAuctionService auctionService;

	public DepositServiceImpl() throws UnsupportedEncodingException {
	}

	@Override
	public int ifPaySingleDeposit(String bidderId, String projId, String bidderName, String projName) {
		try {
			 String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+IDepositService.DEPOSITIN_LIST_MODEL_XML);
	           
				Map m = new HashMap();
				//项目信息
	            AuctionInfo dto= projectInfoService.get(AuctionInfo.class, projId);
	            m.put("dto", dto);
	            //基本信息
	            m.put("date", new Date());
	            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
	            
	            //投标人信息
	            RegisterUser user = this.projectInfoService.get(RegisterUser.class, bidderId);
	            
	            String xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);             //在字串中替换变量
	            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
	            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
	            		Integer.parseInt(bankServerPort));
	            
	            Double inAmount=0D;
	            if(!_ret.equals("")){
	            	//对 _ret进行xml解析
	            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
	            	Head h=jxml.getHead();
	            	if(h.getTransCode().equals("3012")){
	            		//对返回值做处理
	            		String result = jxml.getBody().getResult();
	            		if("1".equals(result)){//查询成功
	            			List<Bank> bankList = jxml.getBody().getBank();
	            			for (Bank bank : bankList) {
	            				String inAmountStr=bank.getInAmount();
//	            				Double inAmount=inAmountStr==null?0D:Double.valueOf(inAmountStr);
	            				System.out.println("===============> user.getLoginName(): "+user.getLoginName());
	            				System.out.println("===============> bank.getInName(): "+bank.getInName());
	            				System.out.println("===============> bank.getInName()==:user.getLoginName():  "+bank.getInName());
	            				
								if(user.getAccount().equals(bank.getInAcct())){//有单笔保证金缴纳且缴纳的金额大于项目保证金
									Double tempAmount=inAmountStr==null?0D:Double.valueOf(inAmountStr);
		            				//inAmount = inAmount+ tempAmount;
									if(tempAmount>inAmount){
										inAmount=tempAmount;
									}
									//查询其银行 账号及开户名
									//付款人户名	InName
									//付款人账号	InAcct
//									if(user.getAccount().equals(bank.getInAcct())){
//										return 1;	
//									}else{
//										return 5;
//									}	
								}
							}
	            		}
	            		
	            		if (inAmount>=dto.getDeposit()){
	            			return 1;
	            		}else {
	            			return 0;
	            		}
	            	}
	            }
		} catch (Exception e) {
			System.out.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}

	
	@Override
	public int returnDepositByProj(String bidderId, String projId, String bidderName, String projName,ComposeIdPK pk) {
		try {
			//项目信息
			AuctionInfo pro = auctionService.get(AuctionInfo.class, projId);
			
			String _xmlStr0 = CommUtil.readStringFromFile(modelPath + "/" + IDepositService.DEPOSIT_BACK_MODEL_XML);
			Map m = new HashMap();
			AuctionInfo dto = auctionService.get(AuctionInfo.class, projId);
			m.put("dto", dto);
			//投标人信息
            RegisterUser user = this.projectInfoService.get(RegisterUser.class, bidderId);
            m.put("user", user);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            //交易流水号
            //DepositReturn deposit = depositService.getDepositReturnByProjIdAndCompanyName(projId, user.getLoginName());
            DepositReturn deposit = projectInfoService.get(DepositReturn.class, pk);
            //System.out.println("++++++++++++++++++++++++++++++++ deposit: "+deposit.getHstSeqNum());
            m.put("deposit", deposit);
            
            //总笔数(默认为1条)
            int totalNum=1;
            m.put("totalNum", totalNum);
            
			String xmlStr = CommUtil.freemarkerProcess(m, _xmlStr0); // 在字串中替换变量
			String _pre = String.format("%06d", xmlStr.getBytes("gbk").length); // 计算字节长度，并以6位前缀补0
			System.out.println("++++++++++++++++++++++++++++++++ _pre+xmlStr: "+_pre+xmlStr);
			String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     // 发送socket// 请求
            		Integer.parseInt(bankServerPort));
			if (!_ret.equals("")) {
				// 对 _ret进行xml解析
				JXml jxml = XmlParserUtil.xmlParserJavaBean(_ret);
				Head h = jxml.getHead();
				if (h.getTransCode().equals("3032")) {
					// 对返回值做判断
					// 是否已提交成功
					String isResult = jxml.getBody().getBank().get(0).getResult();// 0 ：否  ，1 ：是
					return isResult==null?-1:Integer.valueOf(isResult);
				}
            }
		} catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}

	@Override
	public int cutDepositeBy(String bidderId, String projId, String bidderName, String projName) {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public int regToBank(String projId) throws IOException,SocketException{
//		try {
            String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+IDepositService.DEPOSITIN_REG_MODEL_XML);
			Map m = new HashMap();
            AuctionInfo dto= auctionService.get(AuctionInfo.class, projId);
            m.put("dto", dto);
            m.put("centerAccount", centerAccount);
            m.put("transDate", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            String _xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);        //在字串中替换变量
            String _pre=String.format("%06d",_xmlStr.getBytes("gbk").length);				//计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+_xmlStr, bankServerIp, //发送socket 请求
            		Integer.parseInt(bankServerPort));
            if(!_ret.equals("")){											//对 _ret进行xml解析
            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
            	Head h=jxml.getHead();
            	if(h.getTransCode().equals("3002")){  						//验证返回的是3002
            		String _iAcctNo=jxml.getBody().getiAcctNo();
            		String _authCode=jxml.getBody().getAuthCode();
            		if(_iAcctNo!=null && !_iAcctNo.equals("")){
            		    dto.setBankAccount(_iAcctNo);							//对project的返回值 进行处理，保存虚拟帐号。
            		    dto.setBankAuthCode(_authCode);
            		    auctionService.saveOrUpdate(dto);
            		}else{
            		//TODO ：保存数据出错的异常捕获
            		
            		}
            		return 1;
            	}else{
            		//throws Exception
            		return 0;
            	}
            	
            }else{
            	return 0;
            }
	}

	@Override
	public List<Bank> getDepositList(String projId) {
		try {
            String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+IDepositService.DEPOSITIN_LIST_MODEL_XML);
           
			Map m = new HashMap();
			//项目信息
            AuctionInfo dto= projectInfoService.get(AuctionInfo.class, projId);
            m.put("dto", dto);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            String xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);             //在字串中替换变量
            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
            		Integer.parseInt(bankServerPort));
            
            if(!_ret.equals("")){
            	//对 _ret进行xml解析
            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
            	Head h=jxml.getHead();
            	if(h.getTransCode().equals("3012")){  
            		//对返回值做
            		return jxml.getBody().getBank();
            	}
            }
        } catch (Exception e) {
			System.out.println("Error" + e); // 出错，则打印出错信息
			return null;
		}
    			
		return null;
	}

	@Override
	public List<Bank> searchReturnDepositByProj(String projId, String projName) {
		//退款明细查询
		try {
            String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+IDepositService.DEPOSIT_BACK_LIST_MODEL_XML);
            
			Map m = new HashMap();
			//项目信息
            AuctionInfo dto= auctionService.get(AuctionInfo.class, projId);
            m.put("dto", dto);
            //基本信息
            m.put("date", new Date());
            
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            String xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);             //在字串中替换变量
            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
            		Integer.parseInt(bankServerPort));
            
            if(!_ret.equals("")){
            	//对 _ret进行xml解析
            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
            	Head h=jxml.getHead();
            	if(h.getTransCode().equals("3052")){  
            		//对返回值做处理
            		return jxml.getBody().getBank();
            	}
            }
        } catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return null;
		}
		return null;
	}

	@Override
	public int editOpenTime(String projId) {
		try {
			//项目信息
			AuctionInfo pro = auctionService.get(AuctionInfo.class, projId);
			
			String _xmlStr0 = CommUtil.readStringFromFile(modelPath + "/" + IDepositService.PROJECT_OPEN_MODEL_XML);
			//String _pre = String.format("%06d", _xmlStr0.getBytes("gb2312").length); // 计算字节长度，并以6位前缀补0
			Map m = new HashMap();
			AuctionInfo dto = auctionService.get(AuctionInfo.class, projId);
			m.put("dto", dto);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
			String xmlStr = CommUtil.freemarkerProcess(m, _xmlStr0); // 在字串中替换变量
            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
	            		Integer.parseInt(bankServerPort));
			if (!_ret.equals("")) {
				// 对 _ret进行xml解析
				JXml jxml = XmlParserUtil.xmlParserJavaBean(_ret);
				String transCode = jxml.getBody().getTransCode();
				if (transCode.equals("3042")) {
					// 对返回值做判断
					String isResult = jxml.getBody().getResult();// 0 ：否  ，1 ：是
					return isResult==null?-1:Integer.valueOf(isResult);
				}
            }
		} catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}


	/**
	 * 单笔保证金查询(预留) 银行未实现
	 * @param bidderId
	 * @param projId
	 * @return
	 */
	@Deprecated
	private int ifPaySingleDeposit(String bidderId, String projId) {
		try {
			String _xmlStr0 = CommUtil.readStringFromFile(modelPath + "/" + IDepositService.DEPOSITIN_SINGLE_MODEL_XML);
			
			Map m = new HashMap();
			ProjectInfo dto = projectInfoService.get(ProjectInfo.class, projId);
			m.put("dto", dto);
			//投标人信息
            RegisterUser user = this.projectInfoService.get(RegisterUser.class, bidderId);
            m.put("user", user);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
			String xmlStr = CommUtil.freemarkerProcess(m, _xmlStr0); // 在字串中替换变量
			String _pre = String.format("%06d", xmlStr.getBytes("gbk").length); // 计算字节长度，并以6位前缀补0
			String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     // 发送socket// 请求
            		Integer.parseInt(bankServerPort));
			if (!_ret.equals("")) {
				// 对 _ret进行xml解析
				JXml jxml = XmlParserUtil.xmlParserJavaBean(_ret);
				Head h = jxml.getHead();
				if (h.getTransCode().equals("3022")) {
					// 对返回值做判断
					// 是否已缴纳
					String isPay = jxml.getBody().getIsPay();// 0 ：否  ，1 ：是
					String inAmountStr=jxml.getBody().getInAmount();
					Double inAmountS=inAmountStr==null?null:Double.valueOf(inAmountStr);
					if(inAmountS<dto.getPromissMoney()){
						return 0;
					}
					return isPay==null?-1:Integer.valueOf(isPay);
				}
            }
		} catch (Exception e) {
			System.out.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}


	@Override
	public int returnDepositOutSysByProj(Bank bank, String projId,ComposeIdPK2 pk) {
		try {
			//项目信息
			AuctionInfo pro = auctionService.get(AuctionInfo.class, projId);
			String _xmlStr0 ="";
			if(Constant.DEPOSIT_TYPE_BIDDER==pk.getDepositType()){
				_xmlStr0=CommUtil.readStringFromFile(modelPath + "/" + IDepositService.DEPOSIT_BACK_MODEL_XML);//保证金退款
	    	}else{
	    		_xmlStr0=CommUtil.readStringFromFile(modelPath + "/" + "3031_2.xml");//履约保证金退款
	    	}
			
			Map m = new HashMap();
			AuctionInfo dto = auctionService.get(AuctionInfo.class, projId);
			m.put("dto", dto);
			//投标人信息
            //RegisterUser user = this.projectInfoService.get(RegisterUser.class, bidderId);
            RegisterUser user=new RegisterUser();
            user.setLoginName(pk.getCompanyName());
            m.put("user", user);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            //交易流水号
            //DepositReturn deposit = depositService.getDepositReturnByProjIdAndCompanyName(projId, user.getLoginName());
            DepositReturnOut deposit = auctionService.get(DepositReturnOut.class, pk);
            //System.out.println("++++++++++++++++++++++++++++++++ deposit: "+deposit.getHstSeqNum());
            m.put("deposit", deposit);
            
            //总笔数(默认为1条)
            int totalNum=1;
            m.put("totalNum", totalNum);
            
			String xmlStr = CommUtil.freemarkerProcess(m, _xmlStr0); // 在字串中替换变量
			String _pre = String.format("%06d", xmlStr.getBytes("gbk").length); // 计算字节长度，并以6位前缀补0
			System.out.println("++++++++++++++++++++++++++++++++ _pre+xmlStr: "+_pre+xmlStr);
			String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     // 发送socket// 请求
            		Integer.parseInt(bankServerPort));
			if (!_ret.equals("")) {
				// 对 _ret进行xml解析
				JXml jxml = XmlParserUtil.xmlParserJavaBean(_ret);
				Head h = jxml.getHead();
				if (h.getTransCode().equals("3032")) {
					// 对返回值做判断
					// 是否已提交成功
					String isResult = jxml.getBody().getBank().get(0).getResult();// 0 ：否  ，1 ：是
					return isResult==null?-1:Integer.valueOf(isResult);
				}
            }
		} catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}

}
